/**
 * Created with IntelliJ IDEA.
 * User: Hkkkk Guo
 * Date: 2023/2/13
 * Time: 14:52
 * Description:
 */
package com.hangkai.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hangkai.reggie.common.BaseContext;
import com.hangkai.reggie.common.Result;
import com.hangkai.reggie.domain.User;
import com.hangkai.reggie.service.UserService;
import com.hangkai.reggie.utils.SMSUtils;
import com.hangkai.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("手机号是 {}", phone);
            log.info("生成的验证码是 {}", code);
            //通过阿里云提供的API发送短信
            SMSUtils.sendMessage("归海", "SMS_269565672", phone, code);
            //将生成的验证码保存到session
//            session.setAttribute("code", code);
            //将生成的验证码保存在Redis中 5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.success("手机验证码发送成功");
        }
        return Result.success("短信发送失败");
    }

    /**
     * 用户登录 得到手机号和验证码 进行验证码对比
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> userLogin(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码
//        String codeInSession = session.getAttribute("code").toString();
        //从Redis中获取验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        //进行验证码的比对
        if(codeInRedis != null && codeInRedis.equals(code)){
            //如果比对成功 说明登陆成功
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if(user == null){
                // 判断当前手机号是否新用户 如果是 则注册
                User newUser = new User();
                newUser.setPhone(phone);
                userService.save(newUser);
                user = newUser;
            }
            session.setAttribute("user", user.getId());
            //如果登陆成功 删除redis里的验证码
            redisTemplate.delete(phone);
            return Result.success(user);
        }
        return Result.error("登陆失败");
    }

    @PostMapping("/loginout")
    public Result<String> userLogout(HttpSession session){
        session.removeAttribute("user");
        session.removeAttribute("code");
        return Result.success("登出成功");
    }
}
